package com.ysyc.driver_ee.api;

import android.text.TextUtils;

import com.orhanobut.hawk.Hawk;
import com.ysyc.driver_ee.constant.HawkKeys;
import com.ysyc.driver_ee.tools.GsonUtils;
import com.ysyc.driver_ee.tools.LogUtils;
import com.ysyc.driver_ee.tools.MD5Utils;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.TreeMap;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

public class CommonInterceptor implements Interceptor {

    public static final String PARAMS_KEY_APPKEY = "appKey";
    public static final String PARAM_KEY_FORMAT = "format";
    public static final String PARAM_KEY_LANGUAGE = "language";
    public static final String PARAMS_KEY_METHOD = "method";
    public static final String PARAMS_KEY_VER = "ver";
    public static final String PARAMS_KEY_SIGN = "sign";

    public boolean isLog = false;
//测试
//    public static final String APP_KEY = "ghc_APP@!$$Dhqce5qc11365";
//    public static final String APP_SECRET = "APP3y23r8cgs@$!*hcqwcqw";
    //生产


    public static final String APP_KEY = "ysyc_20180820abced!@abc";
    public static final String PARAM_VALUE_FORMAT = "json";
    public static final String APP_SECRET = "20180820abced!@abc";
    public static final String VER_VALUE = "1.0";
    public static final String PARAM_SESSIONKEY = "token";



    public static final String TYPE_STRING = "application/x-www-form-urlencoded;charset=UTF-8";

    private String token;

    @Override
    public Response intercept(Chain chain) throws IOException {
        //获取未添加公共参数钱的requet
        Request oldRequest = chain.request();
        //新的requestBuilder
        Request.Builder newRequestBuilder = null;
        //请求的方法名
        String method = oldRequest.method();
        //请求的url  BASEURL+注解的url
        String url = oldRequest.url().url().toString();
        //获取注解的url
        String requestMethod = url.substring(RetrofitClient.BASE_URL.length(),url.length());
        //请求体string
        String postBodyString = "";

        //创建一个Hashmap 为了放公共参数，给MD5签名用
        HashMap<String,String> params = new HashMap<>();
        //判断是POST请求
        if("POST" == method) {
            //获取原来的requestbody
            RequestBody oldRequestBody = oldRequest.body();

            //吧原requestBody中的参数添加到HashMap中
            if(oldRequestBody instanceof FormBody) {
                for(int i = 0; i < ((FormBody) oldRequestBody).size() ; i++) {
                    String name = ((FormBody) oldRequestBody).encodedName(i);
                    String value = ((FormBody) oldRequestBody).encodedValue(i);
                    params.put(name, URLDecoder.decode(value,"UTF-8"));
                }
            } else {
                newRequestBuilder = oldRequest.newBuilder();
            }

            LogUtils.e("方法名："+requestMethod+"请求参数："+ GsonUtils.mapToJson(params),null);

            //添加完参数后的请求的builder
            FormBody.Builder formBodyBuilder = new FormBody.Builder();

            if(TextUtils.isEmpty(token)) {
                String token = Hawk.get(HawkKeys.TOKEN_KEY);
                if (!TextUtils.isEmpty(token)) {
                    params.put(PARAM_SESSIONKEY,token);
                }
            }
            //添加公共参数
            params.put(PARAMS_KEY_APPKEY,APP_KEY);
            params.put(PARAM_KEY_FORMAT, PARAM_VALUE_FORMAT);
            params.put(PARAMS_KEY_METHOD,requestMethod);
            params.put(PARAMS_KEY_VER,VER_VALUE);
            params.put(PARAM_KEY_LANGUAGE,"1");

            String sign = MD5Utils.md5SignatureEmptyChecked(new TreeMap(params), APP_SECRET);

            params.put(PARAMS_KEY_SIGN,sign);

//            LogUtils.e("方法名："+requestMethod+"请求参数："+ GsonUtils.mapToJson(params));
            //吧公共参数添加到新的builder中
            for (String key : params.keySet()) {
                formBodyBuilder.add(key,params.get(key));
            }

            //构建新的requestBuilder
            newRequestBuilder = oldRequest.newBuilder()
                    .url(RetrofitClient.BASE_URL);
            FormBody requestBody = formBodyBuilder.build();
            postBodyString += ((TextUtils.isEmpty(postBodyString) ? "" : "&")) + bodyToString(requestBody);
            newRequestBuilder.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
            newRequestBuilder.post(RequestBody.create(MediaType.parse(TYPE_STRING),postBodyString));
        } else {
            HttpUrl.Builder builder = oldRequest.url().newBuilder().scheme(oldRequest.url().scheme()).host(oldRequest.url().host());
            newRequestBuilder = oldRequest.newBuilder().method(oldRequest.method(),oldRequest.body())
                    .url(builder.build());
        }

        //新的请求体
        Request newRequest = newRequestBuilder.addHeader("Accept", "application/json")
                .addHeader("Accept-Language", "zh")
                .build();

//        LogUtils.printJson(GsonUtils.mapToJson(params),requestMethod);


        Response response = chain.proceed(newRequest);
        MediaType mediaType = response.body().contentType();
        String content = response.body().string();

//        LogUtils.printJson(content,requestMethod);
            LogUtils.e("方法名：" + requestMethod + "返回结果：" + content,null);

        return response.newBuilder().body(ResponseBody.create(mediaType,content)).build();
    }

    private String bodyToString(RequestBody requestBody) {
        try{
            Buffer buffer = new Buffer();
            if(requestBody != null) {
                requestBody.writeTo(buffer);
            }else {
                return "";
            }
            return buffer.readUtf8();
        }catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
